package DataFile;

import java.nio.ByteBuffer;
import java.util.Formatter;

import ClassData.ConstantPoolMethod_Info;

public class Structure_CP_MethodInfo extends Structure_CP_Constant {

	int methodAdress;
	int realClassAdress;

	ConstantPoolMethod_Info myMethodInfo;	

	public Structure_CP_MethodInfo(ConstantPoolMethod_Info myMethodInfo) {
		this.myMethodInfo=myMethodInfo;
		methodAdress=-1;
	}

	public short getClassIndex() {
		return(myMethodInfo.getNameIndex());
	}

	public short getDescriptorIndex() {
		return(myMethodInfo.getDescriptorIndex());
	}

	public void setRealClassAdress(int newAdress) {
		realClassAdress=newAdress;
	}

	public int getRealClassAdress() {
		return(realClassAdress);
	}

	public void setAdress(int newmethodAdress) {
		methodAdress=newmethodAdress;
	}

	public int getMethodAdress() throws DataFileException {
		if(methodAdress==-1)
			throw new DataFileException(DataFileException.ErrorTypes.ADRESS_NOT_SET);
	
		return(methodAdress);
	}
	
	public int getMemorySize() {
		int size;
		
		size=BYTE_WIDTH;	// Type
		size+=SHORT_WIDTH;	// class name index
		size+=SHORT_WIDTH;	// descriptor index
		size+=ADRESS_WIDTH; // field adress
		size+=ADRESS_WIDTH; // real class adress
		return(size);	
	}

	protected String getMemoryMapAsString() {
//		String returnString;
//		
//		returnString=getAdressAsHexString(baseAdress);
//		returnString+=" : (method info) | size - " + new Formatter().format("%3d",getMemorySize());
//		returnString+=" name : "+myMethodInfo.getNameIndex();
//		returnString+=" descriptor : "+myMethodInfo.getDescriptorIndex();
//		returnString+=" method adress : "+getAdressAsHexString(methodAdress)+" ";
//		returnString+=" real class adress : "+getAdressAsHexString(realClassAdress)+"\n";
		
//		return(returnString);
		
		return "" + new Formatter().format("%s |%14s | size - %3d | name - %3d | descriptor - %3d | %s\n", 
				getAdressAsHexString(baseAdress), 
				"(method info)", 
				getMemorySize(), 
				myMethodInfo.getNameIndex(),
				myMethodInfo.getDescriptorIndex(), 
				"method adress - "+getAdressAsHexString(methodAdress) + 
				"| real class adress - "+getAdressAsHexString(realClassAdress));
		
	}

	/**
	 *  writes data into memory file
	 *  
	 *  @author Tavin
	 *  
	 *  @param fileData buffer for data 
	 */	
	public void writeData(ByteBuffer fileData) {	
		fileData.position(baseAdress-DataFileCreator.BASE_MEMORY_ADRESS);
		fileData.put((byte)myMethodInfo.getType());
		fileData.putShort((short)myMethodInfo.getNameIndex());
		fileData.putShort((short)myMethodInfo.getDescriptorIndex());
		fileData.putInt(methodAdress);
		fileData.putInt(realClassAdress);
	}

	public String getParametersAsString() {
		return(myMethodInfo.getParametersAsString());
	}

}
